package com.example.springboot.highligter;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.*;

import java.io.IOException;

/**
 * Created by tangmayao on 2018/4/4.
 */
public class HighlightUtil {


    public  String highlightStr(Query query, Analyzer a, String fieldName, String txt){
        String str=null;
        QueryScorer queryScorer = new QueryScorer(query);

        //高亮标签
        Formatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>");

        //高亮分析器
        Highlighter hl = new Highlighter(formatter, queryScorer);

        Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
        hl.setTextFragmenter(fragmenter);
        try {
            str = hl.getBestFragment(a, fieldName,txt);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidTokenOffsetsException e) {
            e.printStackTrace();
        }
        if(str == null){
            return txt;
        }
        return str;

    }
}